<?php

	class Backend_ArticleController extends Zend_Controller_Action {
		
		public function init() {
			
			$am = new Model_Authentication();
			$user = $am->getlogguedInformations();
			
			$this->view->action_name = $this->getRequest()->getActionName();
			$this->view->controller_name = $this->getRequest()->getControllername();
		
			// Logged
			if($am->isLoggued()){
				
				// if admin
				$admin = false;
				foreach($user['groups'] as $g) {
					if(strtolower($g) == 'admin') {
						$admin = true;
					}
				}
				
				if(!$admin) {
					$redirector = $this->_helper->getHelper('Redirector');
					$redirector->gotoRoute(array('controller' => 'index', 'action' => 'index'));
				}
				
				$this->view->is_logged = true;
				$this->view->user = $user;
				
			// Not logged
			} else {
				$redirector = $this->_helper->getHelper('Redirector');
				$redirector->gotoRoute(array('module' => 'frontend', 'controller' => 'index', 'action' => 'index'));
			}
			
			$this->view->headLink()
					->appendStylesheet($this->_request->getBaseUrl().'/styles/commun.css')
					->appendStylesheet($this->_request->getBaseUrl().'/styles/template.css')
					->appendStylesheet($this->_request->getBaseUrl().'/styles/backend/article.css');
			
			// Ajax's call
		    $this->_helper->AjaxContext()
		         ->addActionContext('prc-signin', 'json')
		         ->initContext();
		    
		    $this->view->baseUrl = $this->_request->getBaseUrl();
			
			// change layout
            $layout = Zend_Layout::getMvcInstance();
			$layout->setLayout('layout_admin');
			
			// Ajax's call
		    $this->_helper->AjaxContext()
		         ->addActionContext('activate', 'json')
		         ->addActionContext('inactivate', 'json')
		         ->addActionContext('delete', 'json');
		}
		
		public function setAction() {
			
			if($id = $this->_request->getParam('id')) {
				$this->view->headTitle('Hybrid Legacy - Administration - Modifier un article');
			} else {
				$this->view->headTitle('Hybrid Legacy - Administration - Ajouter un article');
			}
					
			$this->view->headLink()
					->appendStylesheet($this->_request->getBaseUrl().'/styles/backend/form.css');
			
			$this->view->jQuery()
					->addJavascriptFile($this->view->baseUrl('/javascript/jquery/jquery.js'))
					->addJavascriptFile($this->view->baseUrl('/javascript/jquery/jquery.form.js'))
					->addJavascriptFile($this->view->baseUrl('/javascript/jquery/jquery.validation.js'))
					->addJavascriptFile($this->view->baseUrl('/javascript/jquery/jquery.validation.rules_custom.js'))
					->addJavascriptFile($this->view->baseUrl('/javascript/jquery/jquery.validation.messages_fr.js'))
					->addJavascriptFile($this->view->baseUrl('/javascript/ckeditor/ckeditor.js'))
					->addJavascriptFile($this->view->baseUrl('/javascript/backend/article-set.js'));
			
			// get article if edition
			if($id) {
				$aM = new Model_Article();
				$filter = array('id' => $id);
				$article = $aM->get($filter);
				if(!is_null($article) and !empty($article)) {
					$article = $article[0];
				} else {
					$article = array();
				}
			
			} else {
				$article = array('id' => 0,
									'title' => '',
									'header' => '',
									'content' => ''
								);
			}
			
			// get categories
			$cM = new Model_ArticleCategory();
			$filter = array('visible' => 1);
			$order = 'name';
			$categories = $cM->get($filter, $order);
			
			$this->view->article = $article;
			$this->view->categories = $categories;
			
		}
		
		public function prcSetAction() {
		
			$id = $this->_request->getParam('id');
			if(isset($id)) {
				$datas = $this->_request->getParams();
			
				// check
				$errors = array();
			
				/*
				 * REQUIRED FIELDS
				 */
			
				// title
				if(is_null($datas['title']) or empty($datas['title'])) {
					$errors[] = 'Titre';
				
				} else {
			
					$udM = new Model_UsersDatas();
				
					// check if is used
					$filter = array('keyname' => strtolower(Model_Tools::noSpecialChars(trim($datas['title'], ' '))));
					$exist = $udM->get($filter);
			
					// if exist and is not user's nickname
					if(isset($exist[0]) and
						($id == $exist[0]['id'])) {
						$errors[] = 'Titre (Déjà utilisé, veuillez en sélectionner un autre)';
					}
				}
			
				// status
				if(is_null($datas['status']) or empty($datas['status'])) {
					$errors[] = 'Status';
				
				} else {
					if($datas['status'] != 'active' and $datas['status'] != 'inactive') {
						$errors[] = 'status';
					}
				}
			
				// category
				if(is_null($datas['category']) or empty($datas['category'])) {
					$errors[] = 'Catégorie';
				}
			
				// header
				if(is_null($datas['header']) or empty($datas['header'])) {
					$errors[] = 'En-tête';
				}
			
				// content
				if(is_null($datas['content']) or empty($datas['content'])) {
					$errors[] = 'Article';
				}
			
				// if errors
				if(!empty($errors)) {
					$message = 'Veuillez vérifier les champs suivant :';
					$message .= '<ul>';
					foreach($errors as $e) {
						$message .= '<li>'.$e.'</li>';
					}
					$message .= '</ul>';
				
					exit(Zend_Json::encode(array('result' => false, 'message' => $message)));
				}
			
				// set article's datas
				$aM = new Model_Article();
				$article = array(	'id_category' => $datas['category'],
									'title' => $datas['title'],
									'keyname' => strtolower(Model_Tools::noSpecialChars($datas['title'])),
									'header' => $datas['header'],
									'content' => $datas['content'],
									'ip' => $_SERVER['REMOTE_ADDR'],
									'status' => $datas['status']
								);
				if($id) {
					$article['update'] = date('Y-m-d H:i:s', time());
					$article['last_modifyer_id'] = $this->view->user['id'];
					$result = $aM->set($id, $article);
				
				} else {
					$article['id_user'] = $this->view->user['id'];
					$article['creation'] = date('Y-m-d H:i:s', time());
					$article['visible'] = 1;
				
					// if admin, set status to active, else to waiting
					$admin = false;
					foreach($this->view->user['groups'] as $g) {
						if(strtolower($g) == 'admin') {
							$admin = true;
						}
					}
					if($admin) {
						$article['status'] = 'active';
					} else {
						$article['status'] = 'waiting';
					}
					$result = $aM->add($article);
				}
			
				if($result) {
			
					// Update user's view information
					$uM = new Model_User();
					$user = $uM->updateInformations($this->view->user['id']);
				
					if($id) {
						$message = 'Modifications effectuées';
					} else {
						$message = 'Article enregistré';
					}
					exit(Zend_Json::encode(array('result' => true, 'message' => 'Modifications effectuées')));
			
				} else {
					exit(Zend_Json::encode(array('result' => false, 'message' => 'Aucune modification effectuée')));
				}
			
			} else {
				exit(Zend_Json::encode(array('result' => false, 'message' => 'Paramètre manquant')));
			}
		
		}
		
		public function activateAction() {
			
			// if admin
			$admin = false;
			foreach($this->view->user['groups'] as $g) {
				if(strtolower($g) == 'admin') {
					$admin = true;
				}
			}
			
			if(!$admin) {
				$this->view->error = 'Vous n\'avez pas les droits d\'accès nécessaires pour pouvoir modifier cette fiche';
				exit(Zend_Json::encode(array('result' => false, 'message' => 'Vous n\'avez pas les droits d\'accès nécessaires pour pouvoir modifier cette fiche')));
			}
			
			if($id = $this->_request->getParam('id')) {
				
				$aM = new Model_Article();
				$datas = array('status' => 'active');
				$result = $aM->set($id, $datas);
				
				if($result) {
					exit(Zend_Json::encode(array('result' => true,
													'message' => 'Modifications effectuées',
													'href' => $this->view->url(array('module' => 'backend', 'controller' => 'article', 'action' => 'inactivate', 'id' => $id), null, true),
													'src' => $this->view->baseUrl().'/images/icons/active.png')));
			
				} else {
					exit(Zend_Json::encode(array('result' => false, 'message' => 'Aucune modification effectuée')));
				}
				
			} else {
				exit(Zend_Json::encode(array('result' => false, 'message' => 'Paramètre manquant')));
			}
			
		}
		
		public function inactivateAction() {
			
			// if admin
			$admin = false;
			foreach($this->view->user['groups'] as $g) {
				if(strtolower($g) == 'admin') {
					$admin = true;
				}
			}
			
			if(!$admin) {
				$this->view->error = 'Vous n\'avez pas les droits d\'accès nécessaires pour pouvoir modifier cette fiche';
				exit(Zend_Json::encode(array('result' => false, 'message' => 'Vous n\'avez pas les droits d\'accès nécessaires pour pouvoir modifier cette fiche')));
			}
			
			if($id = $this->_request->getParam('id')) {
				
				$aM = new Model_Article();
				$datas = array('status' => 'inactive');
				$result = $aM->set($id, $datas);
				
				if($result) {
					exit(Zend_Json::encode(array('result' => true,
													'message' => 'Modifications effectuées',
													'href' => $this->view->url(array('module' => 'backend', 'controller' => 'article', 'action' => 'activate', 'id' => $id), null, true),
													'src' => $this->view->baseUrl().'/images/icons/inactive.png')));
			
				} else {
					exit(Zend_Json::encode(array('result' => false, 'message' => 'Aucune modification effectuée')));
				}
				
			} else {
				exit(Zend_Json::encode(array('result' => false, 'message' => 'Paramètre manquant')));
			}
			
		}
		
		public function deleteAction() {
			
			// if admin
			$admin = false;
			foreach($this->view->user['groups'] as $g) {
				if(strtolower($g) == 'admin') {
					$admin = true;
				}
			}
			
			if(!$admin) {
				$this->view->error = 'Vous n\'avez pas les droits d\'accès nécessaires pour pouvoir modifier cette fiche';
				exit(Zend_Json::encode(array('result' => false, 'message' => 'Vous n\'avez pas les droits d\'accès nécessaires pour pouvoir modifier cette fiche')));
			}
			
			if($id = $this->_request->getParam('id')) {
				
				$aM = new Model_Article();
				$datas = array('visible' => 0);
				$result = $aM->set($id, $datas);
				
				if($result) {
					exit(Zend_Json::encode(array('result' => true, 'message' => 'Article supprimé')));
			
				} else {
					exit(Zend_Json::encode(array('result' => false, 'message' => 'Aucune modification effectuée')));
				}
				
			} else {
				exit(Zend_Json::encode(array('result' => false, 'message' => 'Paramètre manquant')));
			}
			
		}
	
	}
	
?>
